using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;
using MvcShop.Models.Repositories;
using MvcShop.Models;
using xVal.ServerSide;
using MvcShop.Models.ViewDataModels;
using System.ComponentModel;

namespace MvcShop.MVC.Areas.Admin.Controllers
{
    public class PollManageController : Controller
    {
        //
        // GET: /PollManage/
        #region ==== Fields ====
        private IPollOptionRepository<PollOption> _pollOptionRepository;
        private IOnlinePollRepository<OnlinePoll> _onlinePollRepository;
        #endregion

        #region ==== Constructors ====
        public PollManageController(IPollOptionRepository<PollOption> pollOptionRepository, IOnlinePollRepository<OnlinePoll> onlinePollRepository)
        {
            this._pollOptionRepository = pollOptionRepository;
            this._onlinePollRepository = onlinePollRepository;
        }
        #endregion

        #region ==== Index ====
        public ActionResult ManagePoll()
        {
            return View();
        }

        [HttpPost]
        public ActionResult GetListPoll([DefaultValue(1)]int page, [DefaultValue(20)]int rp,
            [DefaultValue("PollOptionId")]string sortname, [DefaultValue("desc")]string sortorder,
            [DefaultValue(null)]string query, [DefaultValue("Subject")]string qtype)
        {
            ICriteria criteria = new NotEqualCriteria("PollOptionId", 0);
            if (!string.IsNullOrEmpty(query))
            {
                if (qtype == "Subject")
                {
                    var op = this._onlinePollRepository.Find(new EqualCriteria("Subject", query.Trim())).FirstOrDefault();
                    criteria = new EqualCriteria("OId", op.OnlinePollId);
                }
                else
                {
                    criteria = new EqualCriteria(qtype, query.Trim());
                }
            }

            OrderType orderType = OrderType.DESC;
            if (sortorder == "asc") orderType = OrderType.ASC;
            Order orderExpr = new Order(orderType, sortname);
            int pCount = this._pollOptionRepository.Count(criteria);

            var iQPO = this._pollOptionRepository.Find(criteria, page, rp, orderExpr);
            var pos = from x in iQPO
                      select new ViewPollOptions
                      {
                          PollOptionId = x.PollOptionId,
                          Color = x.Color,
                          Options = x.Options,
                          Ballots = x.Ballots,
                          Subject = this._onlinePollRepository.Find(new EqualCriteria("OnlinePollId", x.OId)).FirstOrDefault().Subject
                      };
            var nl = from n in pos
                     select new Rows { id = n.PollOptionId, cell = new object[] { n.PollOptionId, n.Subject, n.Options, "#" + n.Color, n.Ballots } };

            return Json(new { total = pCount, page = page, rows = nl });
        }
        #endregion

        #region ==== OnlinePoll ====
        public ActionResult OnlinePollList()
        {
            var ops = this._onlinePollRepository.FindAll();
            return View(ops);
        }

        public ActionResult AddOnlinePoll()
        {
            var onlinePoll = new OnlinePoll { Subject = "IT" };
            return View("EditOnlinePoll", onlinePoll);
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult AddOnlinePoll([Bind(Exclude="OnlinePollId")]OnlinePoll onlinePoll)
        {
            var errors = DataAnnotationsValidationRunner.GetErrors(onlinePoll);
            if (errors.Any())
            {
                new RulesException(errors).AddModelStateErrors(ModelState, "onlinePoll");
                return View("EditOnlinePoll", onlinePoll);
            }

            this._onlinePollRepository.Add(onlinePoll);
            this._onlinePollRepository.SaveChanges();
            return RedirectToAction("ManagePoll");
        }

        public ActionResult EditOnlinePoll(int id)
        {
            var onlinePoll = this._onlinePollRepository.Find(id);
            return View(onlinePoll);
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult EditOnlinePoll(OnlinePoll onlinePoll)
        {
            var errors = DataAnnotationsValidationRunner.GetErrors(onlinePoll);
            if (errors.Any())
            {
                new RulesException(errors).AddModelStateErrors(ModelState, "onlinePoll");
                return View("EditOnlinePoll", onlinePoll);
            }

            this._onlinePollRepository.Update(onlinePoll.OnlinePollId, onlinePoll);
            this._onlinePollRepository.SaveChanges();
            return RedirectToAction("ManagePoll");
        }
        
        public ActionResult DeleteOnlinePoll(int id)
        {
            this._pollOptionRepository.Del(new EqualCriteria("OId",id));
            this._onlinePollRepository.Del(this._onlinePollRepository.Find(id));
            this._onlinePollRepository.SaveChanges();
            return RedirectToAction("ManagePoll");
        }
        #endregion

        #region ==== PollOptions ====
        public SelectList GetListOP()
        {
            var query = this._onlinePollRepository.FindAll();
            return new SelectList(query, "OnlinePollId", "Subject");
        }

        public ActionResult AddPollOption()
        {
            var pollOptions = new PollOption { Options = "IT" };
            ViewData["listOP"] = GetListOP();
            return View("EditPollOption", pollOptions);
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult AddPollOption([Bind(Exclude = "PollOptionId,Ballots")]PollOption pollOption)
        {
            var errors = DataAnnotationsValidationRunner.GetErrors(pollOption);
            if (errors.Any())
            {
                new RulesException(errors).AddModelStateErrors(ModelState, "pollOption");
                return View("EditOnlinePoll", pollOption);
            }
            pollOption.Ballots = 1;

            this._pollOptionRepository.Add(pollOption);
            this._pollOptionRepository.SaveChanges();
            return RedirectToAction("ManagePoll");
        }

        public ActionResult EditPollOption(int id)
        {
            var pollOption = this._pollOptionRepository.Find(id);
            ViewData["listOP"] = GetListOP();
            return View(pollOption);
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult EditPollOption(PollOption pollOption)
        {
            var errors = DataAnnotationsValidationRunner.GetErrors(pollOption);
            if (errors.Any())
            {
                new RulesException(errors).AddModelStateErrors(ModelState, "pollOption");
                return View("EditOnlinePoll", pollOption);
            }

            this._pollOptionRepository.Update(pollOption.PollOptionId, pollOption);
            this._pollOptionRepository.SaveChanges();  
            return RedirectToAction("ManagePoll");
        }     

        public ActionResult DeletePollOption(int id)
        {
            this._pollOptionRepository.Del(this._pollOptionRepository.Find(id));
            this._pollOptionRepository.SaveChanges();

            return RedirectToAction("ManagePoll");
        }

        public ActionResult DelPollOption(string pollOptionId)
        {
            var ids = StringExtensions.ConvertIntList(pollOptionId);
            this._pollOptionRepository.Del(ids);

            return RedirectToAction("ManagePoll");
        }
        #endregion
    }
}
